package com.hjq.demo.ui.activity

import android.content.Intent
import android.graphics.Color
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.text.style.URLSpan
import android.view.View
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.SPUtils
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.hjq.base.BaseDialog
import com.hjq.demo.R
import com.hjq.demo.app.AppActivity
import com.hjq.demo.http.api.UserInfoApi
import com.hjq.demo.http.model.HttpData
import com.hjq.demo.manager.ActivityManager
import com.hjq.demo.other.AppConfig
import com.hjq.demo.other.AppConfig.getBuglyId
import com.hjq.demo.other.AppConfig.isDebug
import com.hjq.demo.other.AppConstant
import com.hjq.demo.ui.dialog.MessageDialog
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallbackProxy
import com.hjq.umeng.UmengClient
import com.hjq.widget.view.SlantedTextView
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import java.util.Locale

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject-Kotlin
 *    time   : 2018/10/18
 *    desc   : 闪屏界面
 */
class SplashActivity : AppActivity() {

    private val debugView: SlantedTextView? by lazy { findViewById(R.id.iv_splash_debug) }

    override fun getLayoutId(): Int {
        return R.layout.splash_activity
    }

    override fun initView() {
    }

    override fun initData() {
        debugView?.let {
            it.setText(AppConfig.getBuildType().uppercase(Locale.getDefault()))
            if (AppConfig.isDebug()) {
                it.visibility = View.VISIBLE
            } else {
                it.visibility = View.INVISIBLE
            }
        }


        // 判断是否已经同意隐私协议 如果没同意过 弹出对话框
        if (!SPUtils.getInstance().getBoolean(AppConstant.PRIVACY_AGREEMENT)) {
            post {
                showPrivacyAgreementDialog()
            }
        } else {
            initOtherData()
        }
    }

    private fun initOtherData() {
        if (true) {
            HomeActivity.start(this@SplashActivity)
            finish()
            return
        }
        // 刷新用户信息
        EasyHttp.post(this)
            .api(UserInfoApi())
            .request(object : HttpCallbackProxy<HttpData<UserInfoApi.Bean?>>(this) {

                override fun onHttpSuccess(data: HttpData<UserInfoApi.Bean?>) {

                }
            })
    }

    private fun showPrivacyAgreementDialog() {


        // 创建提示语句
        val message: String = kotlin.String.format(
            getString(R.string.privacy_agreement_dialog),
            getString(R.string.privacy_agreement_name)
        )


        // 将隐私政策链接设置为蓝色可点击
        val spannableString = SpannableString(message)
        val start: Int = message.indexOf(getString(R.string.privacy_agreement_name))
        val end: Int = start + getString(R.string.privacy_agreement_name).length
        val privacyPolicyUrl = "https://www.umeng.com/page/policy"
        spannableString.setSpan(
            URLSpan(privacyPolicyUrl),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableString.setSpan(
            ForegroundColorSpan(Color.BLUE),
            start,
            end,
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        // 消息对话框
        MessageDialog.Builder(getActivity()!!) // 标题可以不用填写
            .setTitle(getString(R.string.tips)) // 内容必须要填写
            .setSpannableMessage(spannableString)
            .setConfirm(getString(R.string.common_confirm)) // 设置 null 表示不显示取消按钮
            .setCancel(getString(R.string.common_cancel))
            .setCancelable(false)
            .setCanceledOnTouchOutside(false) // 设置点击按钮后不关闭对话框
            //.setAutoDismiss(false)
            .setListener(object : MessageDialog.OnListener {
                override fun onConfirm(dialog: BaseDialog?) {
                    SPUtils.getInstance().put(AppConstant.PRIVACY_AGREEMENT, true)
                    UmengClient.init(ActivityManager.getInstance().getApplication(), "test")
                    //...在这里设置strategy的属性，在bugly初始化时传入
                    val strategy = UserStrategy(this@SplashActivity.application)
                    // 通过UserStrategy设置
                    strategy.setDeviceID(DeviceUtils.getAndroidID())
                    // 通过UserStrategy设置
                    strategy.setDeviceModel(DeviceUtils.getModel())
                    // 获取APP ID并调用初始化方法，Bugly会为自动检测环境并完成配置：
                    CrashReport.initCrashReport(
                        this@SplashActivity.application,
                        getBuglyId(),
                        isDebug()
                    )
                    initOtherData()
                }

                override fun onCancel(dialog: BaseDialog?) {
                    finish()
                }
            })
            .show()
    }

    override fun createStatusBarConfig(): ImmersionBar {
        return super.createStatusBarConfig()
            // 隐藏状态栏和导航栏
            .hideBar(BarHide.FLAG_HIDE_BAR)
    }

    override fun onBackPressed() {
        // 禁用返回键
        //super.onBackPressed();
    }

    override fun initActivity() {
        // 问题及方案：https://www.cnblogs.com/net168/p/5722752.html
        // 如果当前 Activity 不是任务栈中的第一个 Activity
        if (!isTaskRoot) {
            val intent: Intent? = intent
            // 如果当前 Activity 是通过桌面图标启动进入的
            if (((intent != null) && intent.hasCategory(Intent.CATEGORY_LAUNCHER)
                        && (Intent.ACTION_MAIN == intent.action))) {
                // 对当前 Activity 执行销毁操作，避免重复实例化入口
                finish()
                return
            }
        }
        super.initActivity()
    }

    override fun onDestroy() {
        // 因为修复了一个启动页被重复启动的问题，所以有可能 Activity 还没有初始化完成就已经销毁了
        // 所以如果需要在此处释放对象资源需要先对这个对象进行判空，否则可能会导致空指针异常
        super.onDestroy()
    }
}